package com.ccl.keyassistant.fragment;
/*
 *项目名     keyassistant
 *包名       com.ccl.keyassistant.fragment
 *文件名     FingerprintPinCodeDialogFragment
 *创建者     ccl
 *创建时间   2019-03-14 20:06
 *注解       图形解锁对话框
 */

import android.animation.StateListAnimator;
import android.app.DialogFragment;
import android.content.Context;
import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.andrognito.patternlockview.PatternLockView;
import com.andrognito.patternlockview.listener.PatternLockViewListener;
import com.andrognito.patternlockview.utils.PatternLockUtils;
import com.ccl.keyassistant.R;
import com.ccl.keyassistant.activity.LoginActivity;
import com.ccl.keyassistant.db.DBDataHelper;
import com.ccl.keyassistant.entity.BaseModel;
import com.ccl.keyassistant.entity.Pin;
import com.ccl.keyassistant.utils.L;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.crypto.Cipher;

public class PinCodeDialogFragment extends DialogFragment {


    private LoginActivity mActivity;

    private TextView errorMsg;

    private boolean mState = true;

    private PatternLockView mPinPatternLockView;
    private boolean PIN_SUCCESS = false;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (LoginActivity) getActivity();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.pincodeprint_dialog, container, false);
        errorMsg = v.findViewById(R.id.pin_error_msg);
        TextView cancel = v.findViewById(R.id.pin_cancel);
        mPinPatternLockView = (PatternLockView) v.findViewById(R.id.pin_pattern_lock_view);
        mPinPatternLockView.addPatternLockListener(mPatternLockViewListener);

        if (mState) {
            cancel.setText("确认");
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    L.i("1 PIN_SUCCESS:" + PIN_SUCCESS);
                    if (PIN_SUCCESS) {
                        mActivity.onAuthenticated();
                    } else {
                        errorMsg.setText("请设置解锁图形");
                    }
                }
            });
        } else {
            cancel.setText("取消");
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();

                }
            });
        }

//        mPinPatternLockView = (PatternLockView) v.findViewById(R.id.pin_pattern_lock_view);
//        mPinPatternLockView.addPatternLockListener(mPatternLockViewListener);
        return v;
    }

    /**
     * 设置是存储pincode还是验证pincode
     *
     * @param state
     */
    public void setMode(boolean state) {
        this.mState = state;
    }

    /**
     * pinCode的监听事件
     */
    private PatternLockViewListener mPatternLockViewListener = new PatternLockViewListener() {
        @Override
        public void onStarted() {
            Log.d(getClass().getName(), "Pattern drawing started");
        }

        @Override
        public void onProgress(List<PatternLockView.Dot> progressPattern) {
            Log.d(getClass().getName(), "Pattern progress: " +
                    PatternLockUtils.patternToString(mPinPatternLockView, progressPattern));
        }

        @Override
        public void onComplete(final List<PatternLockView.Dot> pattern) {
            Log.d(getClass().getName(), "Pattern complete: " +
                    PatternLockUtils.patternToString(mPinPatternLockView, pattern));

            //依据state判断是存储还是验证，true表示存储
            final DBDataHelper dataHelper = DBDataHelper.getInstance(getContext());
            if (mState) {
                //存储
                ExecutorService executorService = Executors.newSingleThreadExecutor();
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        // 获取数据库连接，写入数据
                        String pincode = PatternLockUtils.patternToSha1(mPinPatternLockView, pattern);
                        Pin pin = new Pin();
                        pin.pincode = pincode;
                        long insert = dataHelper.insert("pincode", pin);
                        if (insert <= 0) {
                            L.w("insert pincode fail");
                        } else {
                            PIN_SUCCESS = true;
                        }
                        L.i("2 PIN_SUCCESS:" + PIN_SUCCESS);
                    }
                });

            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //获取数据库连接，读取数据，判断pincode
                        ArrayList<BaseModel> select = dataHelper.select("pincode", " pincode ",
                                null, null, null, Pin.class);
                        if (select.size() > 0) {
                            Pin pincode = (Pin) select.get(0);
                            if (PatternLockUtils.patternToSha1(mPinPatternLockView, pattern).equals(pincode.pincode)) {
                                //设置当前的状态
                                mPinPatternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT);
                                //跳转到主程序界面
                                mActivity.onAuthenticated();
                            } else {
                                mPinPatternLockView.setViewMode(PatternLockView.PatternViewMode.WRONG);
                                errorMsg.setText("图形错误，请再试一次");
                            }
                        }
                    }
                });

            }


        }

        @Override
        public void onCleared() {
            Log.d(getClass().getName(), "Pattern has been cleared");
        }
    };


    @Override
    public void onPause() {
        super.onPause();

//        if(!mState) {
//            mPinPatternLockView.removePatternLockListener(mPatternLockViewListener);
//            L.i("removePatternLockListener");
//        }
    }

}
